﻿using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Code.UI
{
    public class SkillConfigDialog:MonoBehaviour
    {
        [SerializeField] private TMP_Text _costText;
        [SerializeField] private TMP_Text _nameText;
        [SerializeField] private Image _skillImg;
        [SerializeField] private TMP_Text _moneyText;
        [SerializeField] private TMP_Text _skillDesc;
        [SerializeField] private TMP_Text _skillLevel;

        private UIPlayer _player;

        public UIPlayer Player => _player;

        [SerializeField]private Transform _skillSlotParent;
        private Dictionary<int,SkillSlot> _skillSlotDict = new Dictionary<int,SkillSlot>();

        private void Awake()
        {
            _player=GameObject.FindObjectOfType<UIPlayer>();

            for (int i = 0; i < _skillSlotParent.childCount; i++)
            {
                var skillSlot=_skillSlotParent.GetChild(i).GetComponent<SkillSlot>();
                skillSlot.Index = i+1;
                _skillSlotDict.Add(skillSlot.Index,skillSlot);
                skillSlot.OnSelect += OnSelectSlot;
            }
        }

        private void OnSelectSlot(int index, Skill skill)
        {
            
            if (_player.SkillConfigDict.ContainsKey(skill)) 
            {
                Debug.Log("移除技能");
                _player.SkillConfigDict.Remove(skill);
                _skillSlotDict[index].Reset();
                return;
            }
            else 
            {
                Debug.Log("添加技能");
                _player.SkillConfigDict.Add(skill,index);
                _skillSlotDict[index].SetUI(skill);
            }
        }

        public void Init(Skill skill)
        {
            _costText.text = skill.Cost.ToString();
            _nameText.text = skill.Name;
            _skillImg.sprite = skill.Img;
            _moneyText.text = skill.Money.ToString();
            _skillDesc.text = skill.Desc;
            _skillLevel.text = "技能级别 " + skill.Level.ToString();

            foreach (var item in _player.SkillConfigDict)
            {
                if (_skillSlotDict.TryGetValue(item.Value, out var skillSlot))
                {
                    _skillSlotDict[item.Value].SetUI(item.Key);
                }
            }
        }
        
        public void CloseSkillDialog() 
        {
            StopAllCoroutines();
            this.gameObject.SetActive(false);
        }
    }
}
